/**
 * TalkFun Mutiple Page Vue-loader builder
 */
// webpack.config.js
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const path = require("path");
// const argv = require('argv-options')
// vue-loader
const VueLoaderPlugin = require("vue-loader/lib/plugin");
// 抽离css的插件(使用@next版本)
const ExtractTextPlugin = require("extract-text-webpack-plugin");
// 清道夫
const {
  CleanWebpackPlugin
} = require("clean-webpack-plugin");
// autoprefixer
const autoprefixer = require('autoprefixer')
// 模块入口 => 用于打包所有vue模块
const _entry = require("./webpack_entry");
// webpack Vue config
const setWebpackConf = (config,domain) => {
  // 打包输出目录
  const buildOuterPath = `../vue_dist/${config.modName}/`;
  // 资源相对目录
  const assetsCommonPath = `../vue_dist/assets`;
  // 入口目录
  const entryPath = `../vue_components/src`;
  // return false
  return {
    mode: "production", //'production',
    // 入口
    entry: `${entryPath}/${config.modName}/main.js`,
    watch: true,
    // 出口
    output: {
      // path:  __dirname + "./dist", //打包后的文件存放的地方
      filename: buildOuterPath + "main.js"
    },
    // 路径
    resolve: {
      alias: {
        "@src": path.join(__dirname, "./src"),
        "@util": path.join(__dirname, "./src/utils"),
        "@com": path.join(__dirname, "./src/components"),
      },
      extensions: [".js", ".vue", ".css", ".less"]
    },
    module: {
      rules: [
        // babel-loader @7.x
        {
          test: /\.js$/,
          exclude: /(node_modules|bower_components|static)/,
          use: {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env"],
              // 按需引入vant 
              plugins: [
                [
                  "import",
                  {
                    libraryName: "vant",
                    libraryDirectory: "es",
                    style: true
                  },
                  "vant"
                ]
              ]
            }
          }
        },
        // vue-loader
        {
          test: /\.vue$/,
          use: "vue-loader"
        },
        // css-loader
        {
          test: /\.(less|css)$/,
          exclude: /(static)/,
          use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: [
              'css-loader',
              {
                loader: 'postcss-loader',
                options: {
                  plugins: function () {
                    return [autoprefixer('last 5 versions')]
                  },
                }
              },
              'less-loader'
            ],
          }),
        },
        // 图片loader
        {
          test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
          loader: "url-loader",
          options: {
            limit: 10000,
            name: "[name].[ext]",
            outputPath: `${buildOuterPath}/img/`,
            publicPath: url => `${domain}/templates/vue_dist/${config.modName}/img/${url}`
          }
        },
        // 媒体loader
        {
          test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
          loader: "url-loader",
          options: {
            limit: 10000,
            name: buildOuterPath + "/media/[name].[ext]"
          }
        },
        // 字库loader
        {
          test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
          loader: "url-loader",
          options: {
            limit: 10000,
            name: "[name].[ext]",
            outputPath: `${assetsCommonPath}/font/`,
            publicPath: url => "../../assets/font/" + url
          }
        }
      ]
    },
    plugins: [
      // 这个插件使 .vue 中的各类语言块匹配相应的规则
      new VueLoaderPlugin(),
      // css 输出
      new ExtractTextPlugin(buildOuterPath + `css/main.css`),
      // 清理dist
      new CleanWebpackPlugin(),
      new OptimizeCSSAssetsPlugin({
        assetNameRegExp: /\.css$/g,
        cssProcessor: require("cssnano")
      }),
    ]
  };

};

// 出口
// 例子: yarn build --modules=mod-service-opening
module.exports = (env, argv) => {
  console.warn(argv["modules"]);
  if (!argv["modules"]) {
    console.log("[严重警告]错误 => 入口模块未定义!");
    console.log("[严重警告]请查找该文件是否存在==>", argv["modules"]);
    process.exit();
  }
  let configs = {
    modName: argv["modules"]
  };
  // 打包所有模块
  if (configs.modName == "all-public") {
    configs = _entry;
    return configs.map(item => setWebpackConf(item,'//waimaicn-10063274.file.myqcloud.com/m3.laobanyoudan.com'));
  }
  if (configs.modName == "all-test") {
    configs = _entry;
    return configs.map(item => setWebpackConf(item,''));
  }
  const configObj = setWebpackConf(configs);
  console.log("\n[Packing]正在打包模块 ==>", configObj.entry, "\n");
  return configObj;
};